# lib/stair_master/mapping.rb

require "stair_master/workflow_map/step"
require "stair_master/workflow_map/rules"

module StairMaster
  module WorkflowMap
    extend ActiveSupport::Concern

    included do
      class_attribute :workflow_steps
      class_attribute :workflow_order
      class_attribute :workflow_rules

      self.workflow_steps = {}
      self.workflow_order = []
      self.workflow_rules = {}
    end

    ## TODO: I don't remember what these are for, probably
    ## for rendering the route?
    ##
    # def set_context(view_context)
    #   @view_context = view_context
    # end
    #
    # def get_context
    #   @view_context
    # end

    module ClassMethods

      ## Define the steps that are accessible through this
      ## workflow map.
      ##
      def step(name, label, options={})
        options[:map] = self
        workflow_steps[name.to_sym] = ::StairMaster::WorkflowMap::Step.new( name, label, options )
      end

      ## Define the order of this workflow map
      ##
      def order(*steps)
        steps.each{ |step| workflow_order << step }
        workflow_order
      end

      ## Define a rule for the workflow and attach it to a step
      ##
      ## @example rule :some_rule_name, for: :step_name, action: :skip, if: :method_name
      ## @example rule :some_rule_name, for: :step_name, action: :skip, unless: :method_name
      ##
      ##
      def rule(options={})
        action                    = options.fetch :action, :skip
        step_name                 = options.fetch :for
        workflow_rules[step_name] = [] unless workflow_rules.has_key?(name)

        case action
        when :skip
          if options.fetch(:if)
            type, method_name = [:if, options.fetch(:if)]
          else ## Assume its an unless
            type, method_name = [:unless, options.fetch(:unless)]
          end

          workflow_rules[step_name] << ::StairMaster::WorkflowMap::Rules::SkipRule.new(step_name, type, method_name)
        end
      end
    end
  end
end
